package com.htjx.mall.controllers.interceptors;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.htjx.mall.commons.api.Result;
import com.htjx.mall.commons.models.User;
import com.htjx.mall.controllers.commonapi.AuthorizeList;
import com.htjx.mall.services.UserService;

public class CommonapiAuthInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		long value = AuthorizeList.getCurrentAuthUser(request);
		if (value <= 0) {
			render(response, new Result(401, "请求未经授权"));
			return false;
		}

		User user = userService.findUniqueBy("id", String.valueOf(value));
		if (user == null) {
			render(response, new Result(401, "请求未经授权"));
			return false;
		}
		if (!user.isActive()) {
			render(response, new Result(401, "该账户已被禁用"));
			return false;
		}
		return true;
	}

	private void render(HttpServletResponse response, Object obj) throws IOException {
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(JSON.toJSONString(obj));
		response.getWriter().flush();
	}
}
